import json
import random
import re

from flask import current_app, jsonify
from flask import make_response
from flask import request
from flask import session

from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET

from . import passport_blue
from info import redis_store, db
from info import constants

from datetime import datetime
# 获取短信验证码
# 请求路径: /passport/sms_code
# 请求方式: POST
# 请求参数: mobile, image_code, image_code_id
# 返回值: errno, errmsg


# @passport_blue.route("/passport/sms_code")
# 记得请求方法POST以及在创建蓝图是已经添加了url_prefix = "/passport"

@passport_blue.route("/sms_code", methods=['POST'])
def sms_code():
    # 1. 获取参数
    json_data = request.data.decode('utf-8')
    dict_data = json.loads(json_data)
    mobile = dict_data.get('mobile')
    image_code = dict_data.get("image_code")
    image_code_id = dict_data.get("image_code_id")

    # 2.校验参数
    # 2.1 是否有空值
    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    # 2.2 手机格式
    if not re.match(r'1[3-9]\d{9}', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式有误")

    # 2.3 图片验证码的正确性
    redis_image_code = redis_store.get("image_code:%s" % image_code_id)
    if not redis_image_code:
        return jsonify(errno=RET.PARAMERR, errmsg="图片验证码过期")

    redis_store.delete("image_code:%s" % image_code_id)
    if image_code.upper() != redis_image_code.upper():
        return jsonify(errno=RET.DATAERR, errmsg="图片验证码填写错误")
    # 3.发送短信，数据入库
    sms_code_rand = "%06d" % random.randint(0, 999999)
    # ccp = CCP()
    # result = ccp.send_template_sms(mobile, [sms_code_rand, 5], 1)
    # if result == -1:
    #     return jsonify(errno=RET.DATAERR, errmsg="短信验证码填写错误")
    # bug
    redis_store.setex("sms_code:%s" % mobile, 300, sms_code_rand)
    current_app.logger.debug("sms_code:%s"%sms_code_rand)
    # 4.返回响应
    return jsonify(errno=RET.OK, errmsg="发送成功")


@passport_blue.route('/image_code')
def get_image_code():
    # 1.获取参数,验证码图片id
    cur_id = request.args.get('cur_id')
    pre_id = request.args.get("pre_id")
    if not cur_id:
        return "参数不全"

    if pre_id:
        redis_store.delete("image_code:%s" % pre_id)
    # 2.生成验证码
    name, text, image = captcha.generate_captcha()
    # 3.删除之前的验证码保存当前验证码
    try:
        redis_store.setex('image_code:%s' % cur_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
    except Exception as e:
        current_app.logger.error(e)
        return make_response(jsonify(errno=RET.DATAERR, errmsg='保存验证码失败'))
    # 4.错误处理
    # 5.返回响应
    response = make_response(image)
    response.headers['Content-Type'] = 'image/jpg'
    return response


@passport_blue.route("/register", methods=['POST'])
def register():
    # 1.获取参数
    json_data = request.data.decode("utf-8")
    dict_data = json.loads(json_data)
    mobile = dict_data.get('mobile')
    sms_code = dict_data.get("sms_code")
    password = dict_data.get("password")

    # 2.校验参数
    count = User.query.filter(mobile==mobile).count()
    if count > 0:
        return jsonify(errno=RET.DATAERR, errmsg="用户已存在")
    redis_sms_code = redis_store.get("sms_code:%s" % mobile)

    if not redis_sms_code:
        return jsonify(errno=RET.DATAERR, errmsg="短信验证码已过期")

    if sms_code != redis_sms_code:
        return jsonify(errno=RET.DATAERR, errmsg="短信验证码填写错误")

    # 3.创建用户对象
    try:

        user = User()
        user.nick_name = mobile
        user.password = password
        user.mobile = mobile

        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="注册失败")

    # 4.返回响应
    return jsonify(errno=RET.OK, errmsg="注册成功")


@passport_blue.route("/login", methods=['POST'])
def login():
    # 1. 获取参数
    mobile = request.json.get('mobile')
    password = request.json.get('password')

    # 2. 校验参数
    try:
        user = User.query.filter(User.mobile==mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="查询用户失败")
    if not user.check_password(password):
        return jsonify(errno=RET.DATAERR, errmsg="密码错误")

    # 3. 状态保持
    session['user_id'] = user.id
    session['nick_name'] = user.nick_name
    # 记录最后登陆时间
    # try:
    #     user.last_login = datetime.now()
    #     db.session.commit()
    # except Exception as e:
    #     current_app.logger.error(e)
    user_last_login = datetime.now()

    # 4. 返回响应
    return jsonify(errno=RET.OK, errmsg="登陆成功")


@passport_blue.route("/logout", methods=['POST'])
def logout():
    # 1.清除session信息
    session.pop('user_id', None)
    session.pop('nick_name', None)
    # 2.返回状态
    return jsonify(errno=RET.OK, errmsg="退出登陆")
